package com.practice.sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:选择排序
 * User: YJ
 * Date: 2023-10-25
 * Time: 19:43
 */
public class SelectSort {
    public static void sort(int[] arr) {
        //选择的次数为数组元素个数-1次
        int n = arr.length - 1;
        for (int right = n; right > 0; right--) {
            //设置当前最大（或最小）值为数组最后一个元素的索引
            int max = right;
            //选择最大的
            for (int i = 0; i < right; i++) {
                if (arr[i] > arr[max]) {
                    max = i;
                }
            }
            //交换位置
            if (max != right) {
                swap(arr,max,right);
            }
        }
    }

    public static void swap(int[] arr,int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static void main(String[] args) {
        int[] array = new int[]{6,5,4,3,2,1};
        System.out.println(Arrays.toString(array));
        sort(array);
        System.out.println(Arrays.toString(array));
    }
}
